package com.heima.comment.service.impl;

import com.heima.comment.dtos.CommentDto;
import com.heima.comment.mapper.CommerntMapper;
import com.heima.comment.service.CommentService;
import com.heima.comment.dtos.CommentLikeDto;
import com.heima.comment.dtos.CommentSaveDto;
import com.heima.comment.pojo.Comment;

import com.heima.model.common.dtos.ResponseResult;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class CommentServiceImpl implements CommentService {

    private final MongoTemplate mongoTemplate;

    private final CommerntMapper commerntMapper;

    @Override
    public void saveComment(CommentSaveDto dto) {
        Comment comment = new Comment();

        comment.setArticleId(dto.getArticleId());
        comment.setContent(dto.getContent());
        comment.setCreatedTime(new Date().getTime());
        comment.setUpdatedTime(new Date());
        mongoTemplate.save(comment);

    }

    @Override
    public List<Comment> loadComment(CommentDto dto) {

        int pageNum = 0;
        int pageSize = 10;
        Pageable pageable = PageRequest.of(pageNum, pageSize, Sort.by(Sort.Direction.DESC, "createdTime"));
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .with(pageable);
        List<Comment> commentMgoDBS = mongoTemplate.find(query, Comment.class);
// 返回结果
        return commentMgoDBS;
    }

    @Override
    public void like(CommentLikeDto likeDto) {
        Optional<Comment> commentOptional = commerntMapper.findById(likeDto.getCommentId());
        if (commentOptional.isPresent()) {
            Comment comment = commentOptional.get();
            if (likeDto.getOperation() == 0) {
                comment.setLikes(comment.getLikes() + 1);
            } else {
                comment.setLikes(comment.getLikes() - 1);
            }
            mongoTemplate.save(comment);
            commerntMapper.save(comment);
        }
    }
}
